<template>
  <div class="space-y-8">
    <h2 class="text-2xl font-bold">订单信息</h2>
    
    <!-- 订单详情卡片 -->
    <div class="bg-white p-6 rounded-lg shadow-sm">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="space-y-4">
          <div>
            <span class="text-gray-600">订单编号：</span>
            <span class="font-mono">193198029875661619Z</span>
          </div>
          <div>
            <span class="text-gray-600">订单内容：</span>
            <span>充值金币 600</span>
          </div>
        </div>
        <div class="space-y-4">
          <div>
            <span class="text-gray-600">订单名称：</span>
            <span>充值金币</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-600 mr-2">付款方式：</span>
            <div class="flex items-center">
              <div class="w-6 h-6 bg-blue-500 rounded flex items-center justify-center mr-2">
                <span class="text-white text-xs font-bold">支</span>
              </div>
              <span>支付宝</span>
            </div>
          </div>
        </div>
        <div class="space-y-4">
          <div>
            <span class="text-gray-600">订单金额：</span>
            <span class="text-red-500 font-bold text-xl">6元</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 支付状态 -->
    <div class="bg-white p-6 rounded-lg shadow-sm">
      <h3 class="text-lg font-semibold mb-4">支付</h3>
      <div class="mb-4">
        <span class="text-gray-600">支付倒计时：</span>
        <span class="text-2xl font-mono text-red-500">{{ countdown }}</span>
      </div>
      
      <div class="flex space-x-4">
        <el-button type="primary" @click="openAlipayWindow">
          <div class="flex items-center">
            <div class="w-4 h-4 bg-blue-500 rounded flex items-center justify-center mr-2">
              <span class="text-white text-xs font-bold">支</span>
            </div>
            <el-icon class="mr-1"><Download /></el-icon>
            支付宝付款
          </div>
        </el-button>
        <el-button type="success" @click="openWechatWindow">
          <div class="flex items-center">
            <div class="w-4 h-4 bg-green-500 rounded flex items-center justify-center mr-2">
              <span class="text-white text-xs font-bold">微</span>
            </div>
            <el-icon class="mr-1"><Download /></el-icon>
            微信付款
          </div>
        </el-button>
      </div>
    </div>

    <!-- 注意事项 -->
    <div class="bg-blue-50 p-4 rounded-lg">
      <div class="space-y-2 text-sm">
        <p class="flex items-start">
          <el-icon class="mr-2 mt-0.5" color="#409EFF"><InfoFilled /></el-icon>
          <span>注意：本商品为虚拟内容，购买后不支持退款。如对支付有疑问，请联系客服。</span>
        </p>
        <p class="flex items-start text-red-600">
          <el-icon class="mr-2 mt-0.5" color="#F56C6C"><WarningFilled /></el-icon>
          <span>注意：充值只是购买金币，购买金币后需要去会员界面兑换会员。</span>
          <el-button type="text" @click="goToMembership" class="p-0 ml-1">点击跳转到会员界面</el-button>
        </p>
      </div>
    </div>

    <!-- 订单记录查询 -->
    <div class="bg-white p-6 rounded-lg shadow-sm">
      <h3 class="text-lg font-semibold mb-6">订单记录查询</h3>
      
      <!-- 筛选条件区域 -->
      <div class="mb-6">
        <!-- 收起状态：显示2个条件 + 按钮在同一行 -->
        <div v-if="!showAdvanced" class="grid grid-cols-1 lg:grid-cols-3 gap-4 items-end">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">订单号：</label>
            <el-input v-model="searchForm.orderNo" placeholder="请输入" />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">订单金额：</label>
            <el-input v-model="searchForm.amount" placeholder="请输入" />
          </div>
          <div class="flex items-center space-x-2">
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="searchOrders">查询</el-button>
            <el-button type="text" @click="toggleAdvanced" class="text-blue-600 hover:text-blue-800">
              展开
              <el-icon class="ml-1"><ArrowDown /></el-icon>
            </el-button>
          </div>
        </div>

        <!-- 展开状态：完整的筛选条件 -->
        <div v-else>
          <!-- 第一行：订单号、订单金额、订单名称 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">订单号：</label>
            <el-input v-model="searchForm.orderNo" placeholder="请输入" />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">订单金额：</label>
            <el-input v-model="searchForm.amount" placeholder="请输入" />
          </div>
          <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">订单名称：</label>
              <el-input v-model="searchForm.orderName" placeholder="请输入" />
            </div>
          </div>

          <!-- 第二行：创建时间、过期时间、订单状态 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">创建时间：</label>
              <el-date-picker
                v-model="searchForm.createTime"
                type="date"
                placeholder="请选择"
                class="w-full"
              />
          </div>
          <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">过期时间：</label>
            <el-date-picker
                v-model="searchForm.expireTime"
                type="date"
                placeholder="请选择"
              class="w-full"
            />
          </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">订单状态：</label>
              <el-input v-model="searchForm.status" placeholder="请输入" />
            </div>
        </div>
        
          <!-- 第三行：支付二维码、支付方式、订单描述 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">支付二维码：</label>
              <el-input v-model="searchForm.qrCode" placeholder="请输入" />
        </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">支付方式：</label>
              <el-input v-model="searchForm.paymentMethod" placeholder="请输入" />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">订单描述：</label>
              <el-input v-model="searchForm.description" placeholder="请输入" />
            </div>
          </div>

          <!-- 按钮行 -->
          <div class="flex items-center justify-end space-x-2">
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="searchOrders">查询</el-button>
            <el-button type="text" @click="toggleAdvanced" class="text-blue-600 hover:text-blue-800">
              收起
              <el-icon class="ml-1"><ArrowUp /></el-icon>
            </el-button>
          </div>
        </div>
      </div>

      <!-- 表格工具栏 -->
      <div class="flex items-center justify-between mb-4">
        <div class="text-sm text-gray-600">
          第 1-{{ orderHistory.length }} 条/共 {{ total }} 条
        </div>
        <div class="flex items-center space-x-2">
          <el-tooltip content="刷新" placement="top">
            <el-button size="small" @click="refreshData">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </el-tooltip>
          
          <!-- 密度设置下拉 -->
          <el-dropdown @command="handleDensityChange" trigger="click">
            <el-button size="small">
              <el-icon><Operation /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <div class="px-3 py-2 border-b border-gray-100">
                  <div class="text-sm font-medium text-gray-700">密度</div>
                </div>
                <el-dropdown-item 
                  command="large" 
                  :class="{ 'text-blue-600 bg-blue-50': tableSize === 'large' }"
                >
                  宽松
                </el-dropdown-item>
                <el-dropdown-item 
                  command="default" 
                  :class="{ 'text-blue-600 bg-blue-50': tableSize === 'default' }"
                >
                  中等
                </el-dropdown-item>
                <el-dropdown-item 
                  command="small" 
                  :class="{ 'text-blue-600 bg-blue-50': tableSize === 'small' }"
                >
                  紧凑
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- 列设置下拉 -->
          <el-dropdown trigger="click" :hide-on-click="false">
            <el-button size="small">
              <el-icon><Setting /></el-icon>
            </el-button>
            <template #dropdown>
              <div class="w-48 p-3">
                <div class="flex items-center justify-between mb-3 pb-2 border-b border-gray-100">
                  <span class="text-sm font-medium text-gray-700">列显示</span>
                  <el-button type="text" size="small" @click="resetColumns" class="text-blue-600">
                    重置
                  </el-button>
                </div>
                <div class="space-y-2">
                  <div 
                    v-for="column in columnSettings" 
                    :key="column.key"
                    class="flex items-center"
                  >
                    <el-checkbox 
                      v-model="column.visible" 
                      @change="saveColumnSettings"
                      class="mr-2"
                    />
                    <span class="text-sm text-gray-700">{{ column.label }}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 订单历史表格 -->
      <el-table 
        :data="orderHistory" 
        style="width: 100%" 
        :size="tableSize"
        stripe
        border
      >
        <el-table-column 
          v-if="getColumnVisible('orderNo')"
          prop="orderNo" 
          label="订单号" 
          width="200" 
          show-overflow-tooltip 
        />
        <el-table-column 
          v-if="getColumnVisible('amount')"
          prop="amount" 
          label="订单金额" 
          width="100" 
          align="right"
        >
          <template #default="scope">
            <span class="text-red-500 font-medium">¥{{ scope.row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column 
          v-if="getColumnVisible('product')"
          prop="product" 
          label="订单名称" 
          min-width="120" 
        />
        <el-table-column 
          v-if="getColumnVisible('createTime')"
          prop="createTime" 
          label="创建时间" 
          width="160" 
        />
        <el-table-column 
          v-if="getColumnVisible('expireTime')"
          prop="expireTime" 
          label="过期时间" 
          width="160" 
        />
        <el-table-column 
          v-if="getColumnVisible('status')"
          prop="status" 
          label="订单状态" 
          width="100" 
          align="center"
        >
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          v-if="getColumnVisible('qrCode')"
          label="支付二维码" 
          width="100" 
          align="center"
        >
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 'pending'" 
              size="small" 
              type="primary" 
              @click="showQRCode(scope.row)"
            >
              查看
            </el-button>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column 
          v-if="getColumnVisible('paymentMethod')"
          prop="paymentMethod" 
          label="支付方式" 
          width="100" 
          align="center"
        >
          <template #default="scope">
            <div v-if="scope.row.paymentMethod" class="flex items-center justify-center">
              <div v-if="scope.row.paymentMethod === 'alipay'" class="flex items-center">
                <div class="w-4 h-4 bg-blue-500 rounded flex items-center justify-center mr-1">
                  <span class="text-white text-xs font-bold">支</span>
                </div>
                <span class="text-xs">支付宝</span>
              </div>
              <div v-else-if="scope.row.paymentMethod === 'wechat'" class="flex items-center">
                <div class="w-4 h-4 bg-green-500 rounded flex items-center justify-center mr-1">
                  <span class="text-white text-xs font-bold">微</span>
                </div>
                <span class="text-xs">微信</span>
              </div>
            </div>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>
        <el-table-column 
          v-if="getColumnVisible('description')"
          label="订单描述" 
          width="120" 
          align="center"
        >
          <template #default="scope">
            <span class="text-gray-400">{{ scope.row.description || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewOrder(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex items-center justify-between mt-4">
        <div class="text-sm text-gray-500">
          第 {{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, total) }} 条/共 {{ total }} 条
        </div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100]"
          layout="sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { 
  Download, 
  InfoFilled, 
  WarningFilled, 
  Refresh, 
  Operation, 
  Setting,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const countdown = ref('00:29:53:081')
const showAdvanced = ref(false)
const tableSize = ref('default')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(5)

const props = defineProps<{ order: any }>()

const emit = defineEmits(['tab-switch'])

// 列设置配置
const columnSettings = ref([
  { key: 'orderNo', label: '订单号', visible: true },
  { key: 'amount', label: '订单金额', visible: true },
  { key: 'product', label: '订单名称', visible: true },
  { key: 'createTime', label: '创建时间', visible: true },
  { key: 'expireTime', label: '过期时间', visible: true },
  { key: 'status', label: '订单状态', visible: true },
  { key: 'qrCode', label: '支付二维码', visible: true },
  { key: 'paymentMethod', label: '支付方式', visible: true },
  { key: 'description', label: '订单描述', visible: true }
])

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  amount: '',
  orderName: '',
  createTime: null,
  expireTime: null,
  status: '',
  qrCode: '',
  paymentMethod: '',
  description: ''
})

// 模拟订单数据
const orderHistory = ref([
  {
    orderNo: '192690985181770368',
    amount: '6.00',
    product: '充值金币',
    createTime: '2025-05-26 15:54:44',
    expireTime: '2025-05-26 16:24:44',
    status: 'paid',
    paymentMethod: 'alipay',
    description: '充值600金币'
  },
  {
    orderNo: '192690985181770369',
    amount: '29.90',
    product: '月会员',
    createTime: '2025-05-25 14:30:22',
    expireTime: '2025-05-25 15:00:22',
    status: 'pending',
    paymentMethod: 'wechat',
    description: '购买月会员'
  },
  {
    orderNo: '192690985181770370',
    amount: '99.90',
    product: '年会员',
    createTime: '2025-05-24 10:15:33',
    expireTime: '2025-05-24 10:45:33',
    status: 'cancelled',
    paymentMethod: 'alipay',
    description: '购买年会员'
  },
  {
    orderNo: '192690985181770371',
    amount: '15.90',
    product: '周会员',
    createTime: '2025-05-23 16:20:11',
    expireTime: '2025-05-23 16:50:11',
    status: 'paid',
    paymentMethod: 'wechat',
    description: '购买周会员'
  },
  {
    orderNo: '192690985181770372',
    amount: '12.00',
    product: '充值金币',
    createTime: '2025-05-22 09:45:55',
    expireTime: '2025-05-22 10:15:55',
    status: 'paid',
    paymentMethod: 'alipay',
    description: '充值1200金币'
  }
])

let timer: NodeJS.Timeout | null = null

// 本地存储键名
const STORAGE_KEYS = {
  TABLE_SIZE: 'order_table_size',
  COLUMN_SETTINGS: 'order_column_settings'
}

// 从本地存储加载设置
const loadSettings = () => {
  // 加载表格密度设置
  const savedTableSize = localStorage.getItem(STORAGE_KEYS.TABLE_SIZE)
  if (savedTableSize && ['large', 'default', 'small'].includes(savedTableSize)) {
    tableSize.value = savedTableSize
  }

  // 加载列设置
  const savedColumnSettings = localStorage.getItem(STORAGE_KEYS.COLUMN_SETTINGS)
  if (savedColumnSettings) {
    try {
      const parsed = JSON.parse(savedColumnSettings)
      columnSettings.value.forEach(column => {
        const saved = parsed.find((item: any) => item.key === column.key)
        if (saved !== undefined) {
          column.visible = saved.visible
        }
      })
    } catch (error) {
      console.error('Failed to parse column settings:', error)
    }
  }
}

// 保存表格密度设置
const saveTableSize = () => {
  localStorage.setItem(STORAGE_KEYS.TABLE_SIZE, tableSize.value)
}

// 保存列设置
const saveColumnSettings = () => {
  const settings = columnSettings.value.map(column => ({
    key: column.key,
    visible: column.visible
  }))
  localStorage.setItem(STORAGE_KEYS.COLUMN_SETTINGS, JSON.stringify(settings))
}

// 获取列是否可见
const getColumnVisible = (key: string) => {
  const column = columnSettings.value.find(col => col.key === key)
  return column ? column.visible : true
}

// 重置列设置
const resetColumns = () => {
  columnSettings.value.forEach(column => {
    column.visible = true
  })
  saveColumnSettings()
  ElMessage.success('列设置已重置')
}

// 处理密度变化
const handleDensityChange = (command: string) => {
  tableSize.value = command
  saveTableSize()
  const densityMap: Record<string, string> = {
    large: '宽松',
    default: '中等',
    small: '紧凑'
  }
  ElMessage.success(`表格密度已切换为: ${densityMap[command]}`)
}

// 倒计时逻辑
const startCountdown = () => {
  let totalSeconds = 29 * 60 + 53 // 29分53秒
  
  timer = setInterval(() => {
    if (totalSeconds <= 0) {
      clearInterval(timer!)
      countdown.value = '00:00:00:000'
      ElMessage.warning('支付超时，订单已取消')
      return
    }
    
    const minutes = Math.floor(totalSeconds / 60)
    const seconds = totalSeconds % 60
    const milliseconds = Math.floor(Math.random() * 1000)
    
    countdown.value = `00:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}:${milliseconds.toString().padStart(3, '0')}`
    totalSeconds--
  }, 1000)
}

const openAlipayWindow = () => {
  ElMessage.success('正在打开支付宝支付窗口...')
}

const openWechatWindow = () => {
  ElMessage.success('正在打开微信支付窗口...')
}

const goToMembership = () => {
  ElMessage.info('正在跳转到会员页面...')
  emit('tab-switch', 'my-groups')
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'paid': return 'success'
    case 'pending': return 'warning'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'paid': return '已支付'
    case 'pending': return '待支付'
    case 'cancelled': return '已取消'
    default: return '未知'
  }
}

const toggleAdvanced = () => {
  showAdvanced.value = !showAdvanced.value
}

const resetSearch = () => {
  Object.assign(searchForm, {
    orderNo: '',
    amount: '',
    orderName: '',
    createTime: null,
    expireTime: null,
    status: '',
    qrCode: '',
    paymentMethod: '',
    description: ''
  })
  ElMessage.info('已重置搜索条件')
}

const searchOrders = () => {
  ElMessage.success('查询订单中...')
}

const refreshData = () => {
  ElMessage.success('数据已刷新')
}

const showQRCode = (order: any) => {
  ElMessage.info(`显示订单 ${order.orderNo} 的支付二维码`)
}

const viewOrder = (order: any) => {
  ElMessage.info(`查看订单: ${order.orderNo}`)
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  ElMessage.info(`每页显示 ${size} 条`)
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  ElMessage.info(`切换到第 ${page} 页`)
}

onMounted(() => {
  startCountdown()
  loadSettings()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.space-y-2 > * + * {
  margin-top: 0.5rem;
}

.space-y-4 > * + * {
  margin-top: 1rem;
}

.space-y-8 > * + * {
  margin-top: 2rem;
}
</style>
